import React from 'react'
import './index.css'
import { connect } from 'react-redux'
import { loadAlbum, loadUrl, checkSong, loadLyric, loadDetail,songComment } from '../../store/player.redux'
import {reverseConvert,dataConvert} from '../../util'
import { Toast } from 'antd-mobile'

@connect(
  (state) => ({
    songId: state.player.songId,//歌曲id
    songName: state.player.songName,//歌曲名称
    singer: state.player.singer,//歌手列表
    singerPicUrl: state.player.singerPicUrl,//歌手照片
    albumId: state.player.albumId,//专辑id
    albumName: state.player.albumName,//专辑名称
    albumPicUrl: state.player.albumPicUrl,//专辑logo
    url: state.player.url,//歌曲播放地址
    lyric: state.player.lyric,//歌词
    songs_List:state.songList.songs,//精品歌单歌曲列表
    songs_search:state.search.songs,//搜索结果歌曲列表
    isCheck:state.player.isCheck,//能否播放
    hotComment:state.player.hotComment//热门评论

  }),
  {
    loadAlbum,//专辑信息
    loadUrl,//播放地址
    checkSong,//检查是否能播放
    loadLyric,//加载歌词
    loadDetail,//加载歌曲详情
    songComment//歌曲评论
  }
)
class Player extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      playing:true,//是否正在播放
      currentIndex:0,//歌词播放哪一句的下标
      hideSpeed:true,//是否显示速度菜单
      speed:1,//默认播放速度
      muted:false,//静音  默认静音
      currentTime:0,//当前的播放进度 播放到多少秒
      duration:0,//播放总时长
      songId:0,
      playPercent:0,//播放进度时间比
      volume:100,//默认音量
      from:'',//从哪个组件跳转到播放页面的  是从搜索列表还是精品歌单详情
      fetchCount:0,//请求次数
      hideComment:true//隐藏评论

    };
  }

  componentDidMount() {
    console.log(this.props.location)
    console.log('从哪来',this.props.location.state);
    this.setState({//将从哪个组价跳过转过来的地址存在from当中
      from:this.props.location.state?this.props.location.state.from:''
    })

    let audioId = this.props.match.params.id
    console.log("歌曲id", audioId)
    this.init(audioId)
   
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props.albumId+'======'+nextProps.albumId)
    //判断  前一次加载的ID和后一次加载的ID是否一样 不一样就去重新查询 或者歌手图片为空 也去查询
    if (nextProps.albumId !== this.props.albumId  || nextProps.singerPicUrl === '') {
      //ALBUM
      this.props.loadAlbum(nextProps.albumId)
    }

      //fetchCount为并发数量 如果为5 说明5大接口请求已经完成了 再去判断这首歌是否能播放
    if(this.state.fetchCount===5){
      if((!nextProps.isCheck.success && nextProps.isCheck.message!=='' && nextProps.songId===this.state.songId)|| (nextProps.url===null && nextProps.songId===this.state.songId)){
        console.log(this.state.songId+'不能播放');
        Toast.info('亲爱的，歌曲暂时无法播放',5)
        this.refs.audio.pause()
      }else{
        console.log(this.state.songId+'能播放',nextProps.url);
        this.refs.audio.play();
        this.setState({
          playing:true
        })
      }
    }

  }
  //歌词处理函数
  proccess=(event)=>{
   
    let inner = this.refs.inner;
    let pList = inner.getElementsByTagName('p')//找到所有放歌词的 p标签
    //当前的播放进度
    let audio =event.target//获取事件源
    let currentTime = parseInt(audio.currentTime);
   // 遍历歌词数组  进行对比 当前播放的进度能否在数组里面找到对应歌词的下标
    this.props.lyric.forEach((l,i)=>{
      if(currentTime===parseInt(l.time)){
        this.setState({
          currentIndex:i,
        
        })
        // 找到当前下标 对应的 p 标签的高度 * i 作为inner 父容器的 top值
       
        inner.style.top =  pList[i].offsetHeight * -i + 'px'// 让父容器移动
      }
    })

    //设置当前播放进度和总时长
    //播放时间比
    let playPercent = (currentTime/audio.duration).toFixed(2) * 100
    this.setState({
      currentTime,
      duration:isNaN(audio.duration)?0:audio.duration,
      playPercent
    })

  }
  //播放与暂停的控制
  run =()=>{
    this.setState({
      playing:!this.state.playing
    },()=>{
      if(this.state.playing){
        this.refs.audio.play()//播放
      }else{
        this.refs.audio.pause() //暂停
      }
      
    })
  }

  //速度菜单显示与切换
  toggleSpeed=()=>{
    this.setState({
      hideSpeed:!this.state.hideSpeed
    })
  }
//改变播放速度
  changeSpeed=(currentSpeed)=>{
    this.refs.audio.playbackRate = currentSpeed// 改变歌曲速度 playbackRate： 视频和音频调速属性 
    this.setState({
      speed:currentSpeed
    })

  }

  //静音设置
  setMuted=()=>{
    this.setState({
      muted:!this.state.muted
    },()=>{
      this.refs.audio.muted=this.state.muted
    })
  }

  //音量调节  绑定在音量父元素  黑色条上面
  setVolume=(e)=>{
    //获取鼠标坐标到父容器的距离
    let parent = e.currentTarget;// currentTarget绑定的标签是父元素  获取的是父元素  如果使用target则是指被触发的元素  如果点击到了子元素身上 就获取到了子元素
    let sub = e.pageX-parent.getBoundingClientRect().left//鼠标点击的位置到父元素的left
    //进度百分比
     let per = parseInt(sub / parent.clientWidth * 100)
    console.log('当前音量', per)
    this.refs.audio.volume=(per/100)//设置音量
    this.setState({
      volume:per
    })
  }

  //播放进度
  setProgress=(e)=>{
    let parent = e.currentTarget;
    let sub = e.pageX-parent.getBoundingClientRect().left
    let per = (sub /parent.clientWidth).toFixed(2)

    this.refs.audio.currentTime= this.state.duration * per
    this.setState({
      currentTime:per 
    })
  }

  //上一曲
  prev=()=>{
    let s = this.getIndex()
    if(s.index===-1 || s.index===0){
      Toast.info('暂无上一曲',2);
    }else{
      let prevIndex = s.index-1
      let prevSong= s.songs[prevIndex]
      this.init(prevSong.id)
    }
  }
  //下一曲
  next =()=>{
    let s = this.getIndex()
    if(s.index===-1 || s.index===s.songs.length-1){
      Toast.info('暂无下一曲',2);
    }else{
      let nextIndex = s.index+1
      let nextSong= s.songs[nextIndex]
      this.init(nextSong.id)
    }
  }

  // 让所有的都加载完成
  init=(audioId)=>{
    this.setState({fetchCount:0})
    this.props.loadDetail(audioId,this.calcCount)//加载歌曲详情信息  取到专辑id
    this.props.loadUrl(audioId,this.calcCount)//加载播放地址
    this.props.checkSong(audioId,this.calcCount)//歌曲是否能播放
    this.props.loadLyric(audioId,this.calcCount)// 加载歌词
    this.props.songComment(audioId,this.calcCount)//加载歌曲评论
    this.setState({
      songId:audioId
    })
  }

  //请求次数累加 没请求一次 加一次
  calcCount=()=>{
    this.setState({
      fetchCount:this.state.fetchCount+1
    })
  }

  //根据当前歌曲id去对应的歌单列表里寻找其所在的下标
  getIndex=()=>{
    if(this.state.from.includes('search')){
      let index = this.props.songs_search.findIndex(song=>(
        song.id===this.props.songId
      ))
      return {index,songs:this.props.songs_search}//返回下标 并把搜索歌曲的歌单返回到songs中
    }else if(this.state.from.includes('songList')){
      let index = this.props.songs_List.findIndex(song=>(
        song.id===this.props.songId
      ))
      return {index,songs:this.props.songs_List}
    }else{
      return {index:-1,songs:[]}
    }

  }

  //切换评论的显示与隐藏
  toggleComment=()=>{
    this.setState({
      hideComment:!this.state.hideComment
    },()=>{
        this.refs.comment.style.height = 800+'px'
    })
    
  }

  render() {
    return (
      <div className="player">
        <div className="playHead">
          <p className="p1">
            <img
              src="https://y.gtimg.cn/music/common/upload/t_playsong_ad/1207759.png?max_age=2592000"
              alt=""
            />
          </p>
          <p className="p2">千万正版音乐,海量无损曲库</p>
          <p className="p3">立即使用</p>
        </div>
        <div className="playInfo">
        
          <div className="loging"></div>
          <p className="songPic" style={{ backgroundImage: `url(${this.props.albumPicUrl})` }}>
          </p>
          <div className="playVideo">
            {/* 海报 人名 */}
            <div className="play_song">
              <p className={`singerPic1 ${this.state.playing?"":"pause"}`}>
                <img src={this.props.singerPicUrl} alt="" />
              </p>
              <p className="play_songName">{this.props.songName}</p>
              <p className="play_singeName">
                {
                  this.props.singer.map((s) => (
                    <span key={s.id}>
                      {s.name}
                    </span>
                  ))
                }
              </p>
              <button onClick={this.toggleComment}>评论</button>
            </div>
                {/* 歌词 */}
            <div className="lrc">
              <div className="lrc_box">
                <div className="inner" style={{ top: '100px' }} ref="inner">
                  {
                    this.props.lyric.map((mc,ind) => (
                      <p time={mc.time} key={ind} className={this.state.currentIndex===ind?'active':''} ref="lyricList">{mc.words}</p>
                    ))
                  }
                </div>
              </div>
            </div>
            
            {/* 播放 */}
            <div className="audioBox">
              <audio loop src={this.props.url} ref="audio"   onTimeUpdate={this.proccess} ></audio>
              <h2 className="play_btn_songname">
                {this.props.songName} | 歌手 :{this.props.singer.map((s) => (<span key={s.id}>{s.name}</span>))}
              </h2>

              <div className="play_btn_box">
                <p className="preve iconfont icon-zuobofang" onClick={this.prev}></p>
                <p className={`iconfont "bofang" + ${this.state.playing?"icon-bofang2":"icon-bofang1"} `} onClick={this.run}></p>
                <p className="next iconfont icon-youbofang" onClick={this.next}></p>
              </div>
              {/* <!-- 音量 --> */}
              <div className="play_acound" >
                {/* <p className="['iconfont','muted',isMuted?'icon-jingyin':'icon-yinliang']" ></p> */}
                <p className={`iconfont muted ${this.state.muted?"icon-jingyin":"icon-yinliang"} icon-yinliang`} onClick={this.setMuted} ></p>
                <div className="acoundBox" ref="progressBar" onClick={this.setVolume}>
                  <div className="acoundJindu" ref="progress" style={{width:this.state.volume}}></div>
                </div>
              </div>
              {/* <!-- 进度 --> */}
              <div className="play_plan_box">
                <div className="play_plan" onClick={this.setProgress}>
                  <div className="play_plan_aa" style={{ width: this.state.currentTime+'px' }} ref="playProgress"></div>
                </div>
                {/* reverseConvert(this.state.playPercent)/reverseConvert(this.state.duration) */}
                <p className="play_time">{reverseConvert(this.state.currentTime)} / {reverseConvert(this.state.duration)}</p>
              </div>
              {/* <!-- 速度 --> */}
              <div className="speedBox" onClick={this.toggleSpeed}>
                <span >倍速{this.state.speed}</span>
                {/* <b ref="speedBox">速度</b> */}
                <div className="speed_cont speed_cont1" hidden={this.state.hideSpeed}>
                  <p spedd="0.5" className={this.state.speed===0.5?"speedOn":""} onClick={()=>this.changeSpeed(0.5)}>
                    0.5
                  </p>
                  <p spedd="1" className={this.state.speed===1?"speedOn":""}  onClick={()=>this.changeSpeed(1)}>
                    1.0
                  </p>
                  <p spedd="1.5" className={this.state.speed===1.5?"speedOn":""}  onClick={()=>this.changeSpeed(1.5)}>
                    1.5
                  </p>
                  <p spedd="2" className={this.state.speed===2?"speedOn":""}  onClick={()=>this.changeSpeed(2)} >
                    2.0
                  </p>
                </div>
              </div>
            </div>
          </div>

          <div className='comment'hidden={this.state.hideComment} ref='comment'>
            <h4>热门评论</h4>
              <ul>
                {
                  this.props.hotComment.map(comment=>(
                    <li key={comment.id}>
                  <img src={comment.user.avatarUrl} alt=""/>
                  <span className='user'>{comment.user.nickname}</span>
                  <p>{comment.content}</p>
                  <span className='liked'>{comment.likedCount}人喜欢</span>
                  <time className='time'>{dataConvert(comment.time)}</time>            
                </li>

                  ))
                }
                

              </ul>
            </div>

        </div>
      </div>
    )
  }
}

export default Player